package com.zr.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理验证码生成请求
 * @author lzq
 *
 */
public class ImageAction extends HttpServlet{
	private static final int WIDTH = 120;
	private static final int HEIGHT = 30;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);
		g.setColor(Color.BLUE);
		g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
		drawRandomLine(g);
		
		String imageInfo = drawRandomNum((Graphics2D)g);
		req.getSession().setAttribute("imageInfo", imageInfo);
		resp.setContentType("image/jpg");
		resp.setDateHeader("expries", -1);
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("Pragma", "no-cache");
		ImageIO.write(image, "jpg", resp.getOutputStream());
	}
	
	/**
	 * 在图片上画随机线条
	 * @param g
	 */
	public void drawRandomLine(Graphics g){
		g.setColor(Color.GREEN);
		for (int i = 0; i < 5; i++) {
			int x1 = new Random().nextInt(WIDTH);
			int y1 = new Random().nextInt(HEIGHT);
			int x2 = new Random().nextInt(WIDTH);
			int y2 = new Random().nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	
	/**
	 * 在图片上画验证码
	 * @param g	Graphics2D画图对象
	 * @return	返回验证码字符串
	 */
	private String drawRandomNum(Graphics2D g){
		g.setColor(Color.RED);
		g.setFont(new Font("宋体",Font.BOLD,20));
		String baseNumLetter = "0123456789ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		StringBuffer info = new StringBuffer();
		int x=5;
		String ch;
		for (int i = 0; i < 4; i++) {
			int degree = new Random().nextInt()%30;
			ch = baseNumLetter.charAt(new Random().nextInt(baseNumLetter.length()))+"";
			info.append(ch);
			g.rotate(degree*Math.PI/180,x,20);
			g.drawString(ch,x, 20);
			g.rotate(-degree*Math.PI/180,x,20);
			x += 30;
		}
		return info.toString();
	}
}
